package com.sanjiahantang.youjiarole.module.login.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;

import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.common.beans.PersonBean;
import com.sanjiahantang.youjiarole.module.common.beans.StringBean;
import com.sanjiahantang.youjiarole.module.common.models.IUserModel;
import com.sanjiahantang.youjiarole.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiarole.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiarole.module.join.views.impl.CertificationActivity;
import com.sanjiahantang.youjiarole.module.login.beans.LoginBean;
import com.sanjiahantang.youjiarole.module.login.models.ILoginModel;
import com.sanjiahantang.youjiarole.module.login.models.impl.LoginModel;
import com.sanjiahantang.youjiarole.module.login.views.LoginView;
import com.sanjiahantang.youjiarole.module.login.views.impl.ForgetActivity;
import com.sanjiahantang.youjiarole.module.login.views.impl.RegisterActivity;
import com.sanjiahantang.youjiarole.module.login.views.impl.RegisterSuccessActivity;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by zy on 2017/9/4.
 */

public class LoginPresenter extends BaseMvpPresenter<LoginView>  {
    private ILoginModel loginModel;
    private IUserModel userModel;

    public LoginPresenter() {
        loginModel = new LoginModel();
        userModel = new UserModel();
    }




    public void loadLogin(Context context, final String name, String password, final BaseView.OnLoadListener listener) {
        Map<String, String> params = new HashMap<>();
        params.put("phone", name);
        params.put("password", password);
        params.put("type", "0");
        mView.showProgress();
        loginModel.doLogin(context, params, new CallBack<LoginBean>() {

            @Override
            public void onSuccess(LoginBean response, final Context context, Object tag) {
                hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(RESPONSE_CODE_SUC);
                    final String key = response.getData().getSession().getToken();
                    SPUtils.put(context, SPConfig.KEY, key);
                    if (response.getData().getSession().getUserSessionDto().getUserName() != null) {
                        SPUtils.put(context, SPConfig.USERNAME, response.getData().getSession().getUserSessionDto().getUserName());
                    }
                    String phone = response.getData().getSession().getUserSessionDto().getPhone();
                    SPUtils.put(context, SPConfig.PHONE, phone);
                    String roleId = response.getData().getSession().getUserSessionDto().getRoleId();
                    SPUtils.put(context, SPConfig.ROLE_ID, roleId);
                    ConfigValue.DATA_KEY = key;
                    ConfigValue.PHONE = phone;
                    JPushInterface.setAlias(context, 0, phone);
                    List<LoginBean.Role> roleList = response.getData().getSession().getUserSessionDto().getRoleList();
                    Set<String> set = new HashSet<>();
                    set.add("0");

                    for (LoginBean.Role role : roleList) {
                        if (role.getRoleState() == 2) {
                            set.add(String.valueOf(role.getRoleId() + 2));
                        }
                    }
                    JPushInterface.setTags(context, 0, set);
                    if (JPushInterface.isPushStopped(context)){
                        JPushInterface.resumePush(context);
                    }
                    mView.showProgress();
                    Map<String, String> param = new HashMap<>();
                    param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
                    param.put(KEY_ROLE_ID, "" + SPUtils.get(context, SPConfig.ROLE_ID, ""));
                    param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
                    userModel.loadUserInfo(context, param, new CallBack<PersonBean>() {
                        @Override
                        public void onSuccess(PersonBean response, Context context, Object tag) {
                            if (mView == null)return;
                            mView.hideProgress();
                            if (response.getCode() == RESPONSE_CODE_SUC) {
                                Intent mIntent = new Intent(ConfigValue.ACTION_ALTER_CARTGOODS_NUMS);
                                mIntent.putExtra("cartgoodsnum", "0");
                                //发送广播
                                context.sendBroadcast(mIntent);

                                Intent intent;
                                intent = new Intent(context, MainActivity.class);
                                context.startActivity(intent);
                                ((Activity)context).finish();
                            }
                        }

                        @Override
                        public void onFailure(String message) {
                            if (mView == null)return;
                            mView.hideProgress();
                        }
                    });

                } else {
                    listener.onLoad(RESPONSE_CODE_TIME_OUT);
                    Utils.showToast(context, response.getMessage() == null ? "登录失败" : response.getMessage());
                }
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
                listener.onLoad(RESPONSE_CODE_TIME_OUT);
            }
        });
    }

    public void toRegister(BaseMvpActivity context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        context.startActivity(intent);
        context.finish();
    }

    public void toForget(Context context) {
        Intent intent = new Intent(context, ForgetActivity.class);
        context.startActivity(intent);
    }

    /**
     * 获取验证码
     *
     * @param context
     * @param name
     * @param s
     */
    public void setSendCodeView(Context context, String name, String s) {
        Map<String, String> params = new HashMap<>();
        params.put(KEY_PHONE, name);
        mView.showProgress();
        loginModel.senMessageCode(context, params, new VerificationCodeCallBack());
    }

    //忘记密码按钮
    public void submitData(Context context, String code, String name, String password, String s) {
        Map<String, String> params = new HashMap<>();
        params.put("phone", name);
        params.put("pwd", password);
        params.put("identifyingCode", code);
        mView.showProgress();
        loginModel.doforgetPassword(context, params, new RegisterCallBack(context));


    }

    public void doRegister(Context context, String name, String password,String payPassword, String code) {
        Map<String, String> params = new HashMap<>();
        params.put(KEY_PHONE, name);
        params.put(LoginView.KEY_PASSWORD, password);
        params.put("payPwd",payPassword);
        params.put(LoginView.KEY_identifyingCode, code);
        mView.showProgress();
        loginModel.doRegister(context, params, new RegisterCallBack(context));
    }

    //找回密码
    public void findPassword(final Context context, final String phone, final String pwd, String identifyingCode) {
        final Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        params.put("pwd", pwd);
        params.put("identifyingCode", identifyingCode);
        mView.showProgress();
        userModel.findPassword(context, params, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    Utils.showToast(context, response.getMessage());
                    ((BaseMvpActivity) context).finish();

                } else {
                    Utils.showToast(context, response.getMessage());
                }
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
                Utils.showToast(context, message);
            }
        });
    }

    public void setForgetSendCodeView(Context context, String name, String s) {
        Map<String, String> params = new HashMap<>();
        params.put(KEY_PHONE, name);
        mView.showProgress();
        loginModel.setForgetSendCodeView(context, params, new VerificationCodeCallBack());
    }

    //注册回调
    private class RegisterCallBack implements CallBack<StringBean> {
        private Context context;

        public RegisterCallBack(Context context) {
            this.context = context;
        }

        @Override
        public void onSuccess(StringBean response, Context context, Object tag) {
            hideProgress();
            if (response == null || response.getCode() == RESPONSE_CODE_FAIL) {
                if (response == null) {
                    Utils.showToast(context, "注册失败");
                } else {
                    Utils.showToast(context, response.getMessage());
                }
                return;
            }
            if (response.getCode() == RESPONSE_CODE_SUC) {
                Utils.showToast(context, response.getMessage());
                //注册成功后调登录接口

                loginModel.doLogin(context, (Map<String, String>) tag, new CallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean response, final Context context, Object tag) {
                        hideProgress();
                        if (response.getCode() == RESPONSE_CODE_SUC) {
                            final String key = response.getData().getSession().getToken();
                            final String phone = response.getData().getSession().getPhone();
                            Intent intent = new Intent(context, RegisterSuccessActivity.class);
                            intent.putExtra(KEY_TOKEN, key);
                            intent.putExtra(KEY_PHONE, phone);
                            context.startActivity(intent);
                            ((Activity)context).finish();

//                            if (response.getData().getSession().getUserSessionDto().getRoleState() == 0){
//                                //未申请
//                                Utils.showDialog((Activity) context, "提示", "正在审核中，请耐心等待", "", "切换账号",1, new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//                                        Utils.dismissDialog();
//                                    }
//                                });
//
//                            }else if (response.getData().getSession().getUserSessionDto().getRoleState() == 1){
//                                //审核中
//
//                                //未申请
//                                Utils.showDialog((Activity) context, "提示", "您尚未认证加盟信息", "切换账号", "去认证", new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View view) {
//                                        Utils.dismissDialog();
//                                        switch (view.getId()){
//                                            case R.id.txtDialogSure:
//                                                context.startActivity(new Intent(context,CertificationActivity.class)
//                                                        .putExtra(KEY_TOKEN,key)
//                                                        .putExtra(KEY_PHONE,phone)
//                                                );
//                                                ((Activity) context).finish();
//                                                break;
//                                            case R.id.txtDialogCancel:
//                                                break;
//                                        }
//                                    }
//                                });
//
//
//
//                            }else{
                            SPUtils.put(context, SPConfig.KEY, key);
                            if (response.getData().getSession().getUserSessionDto().getUserName() != null){
                                SPUtils.put(context, SPConfig.USERNAME, response.getData().getSession().getUserSessionDto().getUserName());
                            }
                            SPUtils.put(context, SPConfig.PHONE, phone);
                            String roleId = response.getData().getSession().getUserSessionDto().getRoleId();
                            SPUtils.put(context, SPConfig.ROLE_ID, roleId);
                            ConfigValue.DATA_KEY = key;
                            List<LoginBean.Role> roleList = response.getData().getSession().getUserSessionDto().getRoleList();
                            Set<String> set = new HashSet<>();
                            set.add("0");

                            for (LoginBean.Role role : roleList){
                                if (role.getRoleState() == 2){
                                    set.add(String.valueOf(role.getRoleId() + 2));
                                }
                            }
                            JPushInterface.setTags(context,0,set);
                            JPushInterface.setAlias(context,0,phone);
                            if (JPushInterface.isPushStopped(context)){
                                JPushInterface.resumePush(context);
                            }
                            ConfigValue.PHONE = phone;
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        hideProgress();
                    }
                });
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }

    private void hideProgress() {
        if (mView != null) {
            mView.hideProgress();
        }
    }

    //验证码回调
    private class VerificationCodeCallBack implements CallBack<StringBean> {
        @Override
        public void onSuccess(StringBean response, Context context, Object tag) {
            hideProgress();
            if (response.getCode() == RESPONSE_CODE_SUC) {
                Utils.showToast(context, response.getMessage());
            } else {
                Utils.showToast(context, response.getMessage());
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }
}
